import wx
import  wx.gizmos   as  gizmos
import wx.lib.sized_controls as sc
import  wx.lib.filebrowsebutton as filebrowse
from wx.lib.mixins.listctrl import CheckListCtrlMixin, TextEditMixin
from matplotlib._pylab_helpers import Gcf

from iplot.mpl.wx_utils import bind
from iplot.utils.gui import CaptionCtrl
from iplot.mpl.debug import DEBUG_MSG

from numpy.lib.function_base import iterable

from wx.lib import sheet

class LineSelector(wx.ListCtrl,CheckListCtrlMixin,TextEditMixin):
    def __init__(self, parent):
        
        
        wx.ListCtrl.__init__(self, parent, -1,size=wx.Size(500,300),style=wx.LC_REPORT|wx.LC_VIRTUAL)
        
        TextEditMixin.__init__(self)
        CheckListCtrlMixin.__init__(self)

        uncheckedbmp = self._CheckListCtrlMixin__CreateBitmap(flag=wx.CONTROL_CHECKABLE)
        checkedbmp = self._CheckListCtrlMixin__CreateBitmap(flag=wx.CONTROL_CHECKED)
        
        
        self.il = wx.ImageList(16,16)
        self.il.Add(uncheckedbmp)
        self.il.Add(checkedbmp)
        self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        

        self._parent = parent
        
        self._items = []
        self._filter = []
        
        #Headers
        self.InsertColumn(0,'line legend')
        self.SetColumnWidth(0,175)
        
        self.InsertColumn(1,'marker')
        self.SetColumnWidth(1,50)
        
        self.InsertColumn(2,'style')
        self.SetColumnWidth(1,50)
        
        self.InsertColumn(3,'color')
        self.SetColumnWidth(1,50)

    def _add_line(self,line):
        item = wx.ListItem()
        item.line = line
        
        #_ctrl = self._add_data_column(name)
        #self._ctrls.append((line,_ctrl))
        #_ctrl_y = self._add_data_column(name+'_y')
        #self._ctrls.append((line,_ctrl_y))
        
        #for ctl in _ctrl:
        #    ctl.Hide()
        
        self._items.append(item)
        

    def _refresh(self,event=None):
        
        _gcf_lines = self._get_all_lines()
        #cleanup for non longer existing lines
        
        for item in self._items:
            line = item.line
            if line not in _gcf_lines:
                #self._lines.pop(i)
                #print "removing ",i
                self._items.remove(item)
                #try:
                #    self._lines.remove(line)
                #except:
                #    pass

        #add new lines
        _lines = [i.line for i in self._items]        
        for line in _gcf_lines:
            if line not in _lines:
                item = wx.ListItem()
                item.line = line
                item.checked = False
                #print "adding ",line       
                self._items.append(item)
                
        #show figure,axes lines selection        
        #self.Layout()
        #self.Fit()
        #self._parent.SendSizeEvent()
        DEBUG_MSG("_refresh", 1, self)
    
        
    def _display(self,lines):
        self._set_filter(lines)
        self.SetItemCount(len(self._filter))
        
        
    def _set_filter(self,lines): 
            _filter = []
            for i, item in enumerate(self._items):
                if item.line in lines:
                    _filter.append(i)
            self._filter = _filter
                    
        
    def _get_all_lines(self):
        _lines = []
        for figwin in Gcf.get_all_fig_managers():
            fig = figwin.frame.figure
            for axes in fig.axes:
                lines = axes.lines
                for line in lines:
                    _lines.append(line)
        return _lines
    
    def _get_item(self,row):
        return self._items[self._filter[row]]
    
    def OnGetItemText(self,index,col):
        #print 'item: ',item, 'col: ',col
        item = self._items[self._filter[index]]
        line = item.line
        #print 'line: ',line 
        if col == 0:
            return line.get_label()
        elif col == 1:
            return line.get_marker()
        elif col == 2:
            return line.get_ls()
        elif col == 3:
            return line.get_color()
        else:
            return ''
#        
    def OnGetItemImage(self, index):
        item = self._items[self._filter[index]]
        if item.checked:
            return 1
        else:
            return 0
#
#    
    def OnGetItemAttr(self, item):
        return None
    
    def OnCheckItem(self, index, flag):
        item = self._items[self._filter[index]]
        item.checked = flag
        
    def SetVirtualData(self,row,col,text):
        item = self._get_item(row)
        if col == 0:
            item.line.set_label(text)
        elif col == 1:
            item.line.set_marker(text)
        elif col ==2:
            item.line.set_ls(text)
        elif col == 3:
            item.line.set_c(text)
            
        self.Refresh()
        item.line.axes.figure.canvas.draw()
    
    def get_selected(self):
        _lines = []
        for item in self._items:
            if item.checked:
                _lines.append(item.line)
        return _lines
    
    def deselect_all(self):
        for item in self._items:
            item.checked = False
        self.Refresh()
        
#Check out MVCTree        
class PropertyBrowser(gizmos.TreeListCtrl):
    def __init__(self, parent,obj=None):
        gizmos.TreeListCtrl.__init__(self, parent, -1,size=wx.Size(500,300),style=
                                     wx.TR_DEFAULT_STYLE|
                                     wx.TR_FULL_ROW_HIGHLIGHT|
                                     wx.TR_ROW_LINES
                                     )
        self.AddColumn('attribute')
        self.AddColumn('value')
        self.SetMainColumn(0)
        self.SetColumnWidth(0, 175)
        
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDED,self.OnExpand)
        self.Bind(wx.EVT_TREE_END_LABEL_EDIT,self.OnEdit)
        
    def SetRoot(self,obj,rootname="The Root"):
        self.DeleteRoot()
        self.root = self.AddRoot(rootname)
        self.SetItemData(self.root,wx.TreeItemData(obj))
        self._expand(self.root)
        self.Expand(self.root)
        
    def _set_has_children(self,item):
        obj = self.GetItemData(item).GetData()
        if type(obj) in [list,dict,tuple] or getattr(obj,'__dict__',None) is not None:
            self.SetItemHasChildren(item,True)
            return True
        else:
            return False

    def _expand(self,item):
        
        if self.GetChildrenCount(item) != 0:
            return
        
        #print "item to be expanded ", self.GetItemText(item)
        #print id(item)
        obj = self.GetItemData(item).GetData()
        #print item
        #print 'object to be expanded ', obj
            
        if type(obj) in [list,tuple]:
            #print 'iterable'
            for o in obj:
                child = self.AppendItem(item,self.GetItemText(item))
                self.SetItemData(child,wx.TreeItemData(o))
                self._set_has_children(child)
            return

        for k in obj.__dict__.keys():
            #print k
            if type(k) != type(''):
                continue
            if k.startswith('_'):
                continue
            child = self.AppendItem(item,k)
            o = getattr(obj,k)
            self.SetItemData(child,wx.TreeItemData(o))
            #print id(child),':',k
            if self._set_has_children(child):
                pass
            else:
                self.SetItemText(child,str(o),1)
                
    def OnExpand(self,evt=None):
        item = evt.GetItem()
        self._expand(item)
        self.Expand(item)
        
    def OnActivate(self,evt=None):
        print 'activated'
        self.EditLabel(evt.GetItem(),1)
        
    def OnEdit(self,evt=None):
        item = evt.GetItem()
        attr = self.GetItemText(item,0)
        val = self.GetItemText(item,1)
        obj = self.GetItemData(self.GetItemParent(item)).GetData()
        
        print obj
        print type(getattr(obj,attr,None))
        print attr
        print val
        if type(getattr(obj,attr,None)) in [str,unicode]:
            print obj
            setattr(obj,attr,val)
            
class PropertyDialog(wx.Dialog):
    def __init__(
            self, parent, id, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
            useMetal=False,            
            ):
        # Instead of calling wx.Dialog.__init__ we precreate the dialog
        # so we can set an extra style that must be set before
        # creation, and then we create the GUI object using the Create
        # method.
        pre = wx.PreDialog()
        #pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
        pre.Create(parent, id, title, pos, size, style)

        # This next step is the most important, it turns this Python
        # object into the real wrapper of the dialog (instead of pre)
        # as far as the wxPython extension is concerned.
        self.PostCreate(pre)
        
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.browser = PropertyBrowser(self)
        
        self.sizer.Add(self.browser, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        
class SelectorDialog(wx.Dialog):
    def __init__(
            self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False,            
            ):
        
        self._figs = []
        self._axes = []

        # Instead of calling wx.Dialog.__init__ we precreate the dialog
        # so we can set an extra style that must be set before
        # creation, and then we create the GUI object using the Create
        # method.
        pre = wx.PreDialog()
        #pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
        pre.Create(parent, ID, title, pos, size, style)

        # This next step is the most important, it turns this Python
        # object into the real wrapper of the dialog (instead of pre)
        # as far as the wxPython extension is concerned.
        self.PostCreate(pre)

        # This extra style can be set after the UI object has been created.
        if 'wxMac' in wx.PlatformInfo and useMetal:
            self.SetExtraStyle(wx.DIALOG_EX_METAL)
            
        # Now continue with the normal construction of the dialog
        # contents
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        
        self.selectorsz = wx.BoxSizer(wx.HORIZONTAL)
        self.figctl = CaptionCtrl(self,wx.Choice, captxt="Figure:"
                                , size=(100,45)
                                , choices = self._get_figures()
                                )
        self.figctl.control.Select(wx.NOT_FOUND)
        fignum = self.figctl.control.GetStringSelection()
        bind(self.figctl.control,wx.EVT_CHOICE, self._on_figure_change)
        self.selectorsz.Add(self.figctl,0,wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5)
        self.axesctl= CaptionCtrl(self,wx.Choice, captxt="Axes:"
                                , size=(100,45)
                                , choices = self._get_axes(fignum)
                                )
        self.axesctl.control.Select(wx.NOT_FOUND)
        #sizer.Add(self.axesctl,0,wx.ALIGN_CENTRE|wx.ALL, 5)
        bind(self.axesctl.control,wx.EVT_CHOICE, self._on_axes_change)
        self.selectorsz.Add(self.axesctl,0,wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5)
        
        #self.desel = wx.Button(self,-1,label='Deselect')
        #bind(self.desel,wx.EVT_BUTTON, self._on_desel)
        #selectorsz.Add(self.desel,0,wx.ALIGN_RIGHT|wx.GROW|wx.ALL, 5)

        self.sizer.Add(self.selectorsz, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        #self.linesel = LineSelector(self)

        #self.sizer.Add(self.linesel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        #self._on_figure_change()
        #self._on_axes_change()
        
        self.SetSizer(self.sizer)
        self.selectorsz.Layout()
        self.sizer.Layout()
        
        
    def _refresh(self):
        
        #remove non existing fignum
        for i,fig in enumerate(self._figs):
            if fig not in self._get_figures():
                j = self.figctl.control.FindString(str(fig.number))
                self.figctl.control.Delete(j)
                self._figs.pop(i)
        
        #add new fignum
        for fig in self._get_figures():
            if fig not in self._figs:
                self.figctl.control.Append(str(fig.number))
                self._figs.append(fig)
        if self.figctl.control.GetSelection() is wx.NOT_FOUND:
            self.figctl.control.Select(0)
        
        self._refresh_axes()
        #self._refresh_lines()
        
        self.SendSizeEvent()
        self.Fit()
        
    def select_figure(self,fig):
        fignumstr = str(fig.number)
        self.figctl.control.SetStringSelection(fignumstr)
        self._refresh()

    def _refresh_axes(self):
        fignum = self.figctl.control.GetStringSelection()
        self.axesctl.control.Clear()
        for i,axes in enumerate(self._get_axes(fignum)):
            self.axesctl.control.Append(str(i))
        
        if self.axesctl.control.GetSelection() is wx.NOT_FOUND:
            self.axesctl.control.Select(0)

        
    def _get_figures(self):
        _figs = []
        for figwin in Gcf.get_all_fig_managers():
            _figs.append(figwin.canvas.figure)
        return _figs
            
    
    def _get_axes(self,fignum):
        _axes = []  

        if fignum:    
            fignum = int(fignum)
            fig = Gcf.figs[fignum].canvas.figure
            axes = fig.axes
            for ax in axes:
                _axes.append(ax)
            
            return _axes
        else:
            return _axes
             
    def _on_figure_change(self,event=None):
        self._refresh()
        
    def _on_axes_change(self,event=None):
        #print self.axesctl.control.GetSelection()
        #self.SendSizeEvent()
        self.Fit()

class PlotDialog(SelectorDialog):
    def __init__(
            self, parent, id, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False,            
            ):

        SelectorDialog.__init__(self, parent, id, title, size, pos, style, useMetal)
        
        self.desel = wx.Button(self,-1,label='Deselect')
        bind(self.desel,wx.EVT_BUTTON, self._on_desel)
        self.selectorsz.Add(self.desel,0,wx.ALIGN_RIGHT|wx.GROW|wx.ALL, 5)

        #self.sizer.Add(selectorsz, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        self.linesel = LineSelector(self)

        self.sizer.Add(self.linesel, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        
        self._on_figure_change()
        self._on_axes_change()
        
        #self.SetSizer(self.sizer)
        self.selectorsz.Layout()
        self.sizer.Layout()
        
        
    def _refresh(self):
        
        SelectorDialog._refresh(self)
        self._refresh_lines()
        
        self.SendSizeEvent()
        self.Fit()
            
    def _refresh_lines(self):
        figsel = self.figctl.control.GetStringSelection()
        axsel = self.axesctl.control.GetSelection()
        
        if axsel is not wx.NOT_FOUND:
            lines = self._get_lines(figsel, axsel)
        else:
            lines = []
        
        
        self.linesel._refresh()
        self.linesel._display(lines)
        
    def _on_desel(self,evt=None):
        self.linesel.deselect_all()
        
        
    def _get_lines(self,fignum,axesnum):
        if fignum:
            fignum = int(fignum)
        else:
            return []
        try:
            axesnum = int(axesnum)
        except:
            return []
            
        fig = Gcf.figs[fignum].canvas.figure
        axes = fig.axes[axesnum]
        return axes.lines
        
    def _on_axes_change(self,event=None):
        SelectorDialog._on_axes_change(self, event)
        self._refresh_lines()
        self.SendSizeEvent()
        self.Fit()

class PlotMixDialog(PlotDialog):
    def __init__(
            self, parent, ID, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False,            
            ):
        
        PlotDialog.__init__(self, parent, ID, title, size, pos, style, useMetal)
        
        line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
        self.sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.TOP, 5)
        
        btnsizer = wx.StdDialogButtonSizer()
        if wx.Platform != "__WXMSW__":
            btn = wx.ContextHelpButton(self)
            btnsizer.AddButton(btn)
            
        self.btn_replot = wx.Button(self, id=wx.ID_APPLY, label="Replot")
        self.btn_replot.Disable()
        self.btn_replot.SetHelpText("Replot on current figure...")
        btnsizer.AddButton(self.btn_replot)
        bind(self.btn_replot,wx.EVT_BUTTON,self._on_replot)
        
        self.btn_new_fig = wx.Button(self, id=wx.ID_OK, label='New Figure')
        self.btn_new_fig.SetHelpText("Generate new figure...")
        self.btn_new_fig.SetDefault()
        btnsizer.AddButton(self.btn_new_fig)
        self.Bind(wx.EVT_BUTTON,self._on_new_figure,self.btn_new_fig)
        
        btn = wx.Button(self, wx.ID_CANCEL)
        btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
        btnsizer.AddButton(btn)

        btnsizer.Realize()
        
        self.sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)

        
    def _on_new_figure(self,event=None):
        self._plot()
        #self.Hide()
        self.EndModal(wx.ID_OK)
        
    def _on_replot(self,event=None):
        pass
    
    def _plot(self):
        from matplotlib.pyplot import figure
        from numpy.ma import isMaskedArray
        
        lines = self.linesel.get_selected()
        if len(lines) == 0 :
            return
        
        fig = figure()
        axs = fig.add_subplot(111)
        for line in lines:
            line_axs = line.get_axes()
            xunits = line_axs.xaxis.get_units()
            yunits = line_axs.yaxis.get_units()
            label = line.get_label()
            
            _x = line.get_xdata(1)
            _y =line.get_ydata(1)
            
            if isMaskedArray(_x):
                _x = _x.compressed()
            
            if isMaskedArray(_y):
                _y = _y.compressed()
                
            #print _x, _y
                
            axs.plot(_x,_y,label=label,xunits=xunits,yunits=yunits)
            
            
        
        #    print line.get_xdata()
        #    print line.get_ydata()
        #fig.canvas.draw()
        

class DataSheet(sheet.CSheet):
    def __init__(self,parent):
        sheet.CSheet.__init__(self,parent)
        self.SetNumberCols(0)
        self.SetNumberRows(0)
        
        bind(self,wx.EVT_TEXT_COPY,self._onCopy)
    
    
    def _onCopy(self,evt):
        self.Copy()
        
    def SetCol(self,pos,data):
        
        if iterable(data):
            self.SetNumberRows (  max( self.GetNumberRows(), len(data) ))
            for i,val in enumerate(data):
                self.SetCellValue(i,pos,str(val))

class DataDialog(PlotDialog):        
        def __init__(
            self, parent, id, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False,            
            ):
            
            PlotDialog.__init__(self, parent, id, title, size, pos, style, useMetal)
        
            line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
            self.sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.TOP, 5)
        
            btnsizer = wx.StdDialogButtonSizer()
            if wx.Platform != "__WXMSW__":
                btn = wx.ContextHelpButton(self)
                btnsizer.AddButton(btn)
        
            self.btn_data = wx.Button(self, id=wx.ID_OK, label='OK')
            self.btn_data.SetHelpText("Generate datasheet...")
            self.btn_data.SetDefault()
            btnsizer.AddButton(self.btn_data)
            self.Bind(wx.EVT_BUTTON,self._on_data,self.btn_data)
        
            btn = wx.Button(self, wx.ID_CANCEL)
            btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
            btnsizer.AddButton(btn)

            btnsizer.Realize()
        
            self.sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
            self.figctl.control.Disable()
            
        def _on_data(self,event=None):
            self._show_data()
            self.EndModal(wx.ID_OK)
            
        def _append_data_col(self,dsheet,data,label):
            col = dsheet.GetNumberCols()
            dsheet.AppendCols(1)
            dsheet.SetColLabelValue(col,label)
            dsheet.SetCol(col,data)
            
        def _show_data(self):
            lines = self.linesel.get_selected()
            databook = self.GetParent().databook
            dsheet = DataSheet(databook)
            dsheet.SetPosition(wx.Point(300,300))
            for line in lines:
                self._append_data_col(dsheet,line.get_xdata(),line.get_label()+'_x')
                self._append_data_col(dsheet,line.get_ydata(),line.get_label()+'_y')
                
            databook.AddPage(dsheet,caption='Sheet',select=True)
     
class PlotfileDialog(sc.SizedDialog):
    def __init__(self, parent, id,title):
        sc.SizedDialog.__init__(self, parent, id, title="Plot file", 
                        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        
        pane = self.GetContentsPane()
        pane.SetSizerType("form")
        
        # row 1
        wx.StaticText(pane, -1, "File Entry:")
        self.fbb = filebrowse.FileBrowseButton(
            pane, -1, size=(450, -1), labelText='', fileMode=wx.OPEN )
        self.fbb.SetSizerProps(expand=True)
        
        # row 2
        wx.StaticText(pane, -1, "cols:")
        self.cols = wx.TextCtrl(pane, -1, "0,")
        self.cols.SetSizerProps(expand=True)
        
        wx.StaticText(pane, -1, "units:")
        self.units = wx.TextCtrl(pane, -1, "")
        self.units.SetSizerProps(expand=True)
        
        
        
        wx.StaticText(pane, -1, "comments:")
        self.comments = wx.TextCtrl(pane, -1, "#")
        self.comments.SetSizerProps(expand=True)
        
        wx.StaticText(pane, -1, "skiprows:")
        self.skiprows = wx.TextCtrl(pane, -1, "0")
        self.skiprows.SetSizerProps(expand=True)
        
        wx.StaticText(pane, -1, "checkrows:")
        self.checkrows = wx.TextCtrl(pane, -1, "5")
        self.checkrows.SetSizerProps(expand=True)
        
        wx.StaticText(pane, -1, "delimiter:")
        wschar = ['tab','space']
        self.delimiter = wx.ComboBox(pane, -1, ",",choices=wschar)
        self.delimiter.SetSizerProps(expand=True)
        
        wx.StaticText(pane, -1, "plotfuncs:")
        self.plotfuncs = wx.TextCtrl(pane,-1,'None')
        self.plotfuncs.SetSizerProps(expand=True)
        
        # row 3
        wx.StaticText(pane, -1, "names:")
        self.names = wx.TextCtrl(pane, -1, 'None')
        self.names.SetSizerProps(expand=True)
        
        
        
        # row
        wx.StaticText(pane, -1, "")
        
        # here's how to add a 'nested sizer' using sized_controls
        radioPane = sc.SizedPanel(pane, -1)
        radioPane.SetSizerType("horizontal")
        radioPane.SetSizerProps(expand=True)
        
        # make these children of the radioPane to have them use
        # the horizontal layout
        self.subplots= wx.CheckBox(radioPane, -1, "subplots")
        self.newfig = wx.CheckBox(radioPane, -1, "newfig")
        # end row 5
        
        # add dialog buttons
        self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL))
        
        # a little trick to make sure that you can't resize the dialog to
        # less screen space than the controls need
        self.Fit()
        self.SetMinSize(self.GetSize())

            
class FormatAxesDialog(SelectorDialog):        
        def __init__(
            self, parent, id, title, size=wx.DefaultSize, pos=wx.DefaultPosition, 
            style=wx.DEFAULT_DIALOG_STYLE,
            useMetal=False,            
            ):
            
            SelectorDialog.__init__(self, parent, id, title, size, pos, style, useMetal)
        
            line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
            self.sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM|wx.TOP, 5)
        
            btnsizer = wx.StdDialogButtonSizer()
            if wx.Platform != "__WXMSW__":
                btn = wx.ContextHelpButton(self)
                btnsizer.AddButton(btn)
        
            self.btn_ok = wx.Button(self, id=wx.ID_OK, label='OK')
            self.btn_ok.SetHelpText("")
            self.btn_ok.SetDefault()
            btnsizer.AddButton(self.btn_ok)
            self.Bind(wx.EVT_BUTTON,self._on_ok,self.btn_ok)
        
            btn = wx.Button(self, wx.ID_CANCEL)
            btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
            btnsizer.AddButton(btn)

            btnsizer.Realize()
        
            self.sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
            self.figctl.control.Disable()
            
        def _on_ok(self,event=None):
            self.EndModal(wx.ID_OK)            